import Vue from 'vue'
import Vuex from 'vuex'
import { jwtDecode } from 'jwt-decode'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || null,
    token: localStorage.getItem('token') || null
  },
  getters: {
    userInfo: state => state.userInfo,
    isLoggedIn: state => !!state.token,
    userType: state => state.userInfo ? state.userInfo.userType : ''
  },
  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    LOGOUT(state) {
      state.userInfo = null
      state.token = null
      localStorage.removeItem('token')
    }
  },
  actions: {
    // 登录操作
    login({
      commit
    }, userData) {
      // 实际应用中应该调用后端API进行登录
      // 这里简化处理，假设登录成功后返回用户信息和token
      const userInfo = {
        id: userData.id,
        username: userData.username,
        userType: userData.userType
      }

      commit('SET_USER_INFO', userInfo)

      console.log('store login action 成功完成，返回userInfo');
      return Promise.resolve({
        userInfo
      })
    },
    // 登出操作
    logout({
      commit
    }) {
      commit('LOGOUT')
    },
    // 获取用户信息
    fetchUserInfo({ commit }, userId) {
      // 从请求头Authorization中获取token并移除空格
      return axios.get('/user/info', { params: { id: userId } }).then(response => {
        const token = response.data.data;
        if (token) {
          commit('SET_TOKEN', token);
          try {
            const decodedToken = jwtDecode(token);
            const userInfo = {
              id: decodedToken.id,
              username: decodedToken.username,
              userType: decodedToken.roleName === 'supplier' ? 'supplier' : 'yunying',
              useraccount: decodedToken.useraccount
            };
            console.log("获取到的用户信息:", userInfo);
            commit('SET_USER_INFO', userInfo);
            // 保存用户信息到localStorage
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
            return Promise.resolve(userInfo);
          } catch (error) {
            return Promise.reject(new Error('无效的token'));
          }
        } else {
          return Promise.reject(new Error('未从响应中获取到token'));
        }
      }).catch(error => {
        return Promise.reject(new Error(error.message || '获取用户信息失败'));
      });
    }
  },
  modules: {
  }
})
// 添加axios请求拦截器
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})
